﻿using MES.Desktop.Entities;
using MES.Desktop.IDataAccess;
using MES.Desktop.IService;
using MES.Desktop.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MES.Desktop.Service
{
    public class FuncService : ServiceBase,IFuncService
    {
        IFuncAccess _funcAccess;
        public FuncService(IFuncAccess funcAccess)
        {
            _funcAccess = funcAccess;
        }
        public bool CheckName(string name, int id)
        {
            string json = _funcAccess.CheckName(name, id);
            return this.GetResult<bool>(json);
        }
        public int Delete(string[] id)
        {
            string ids_json = System.Text.Json.JsonSerializer.Serialize(id);
            string json = _funcAccess.Delete(ids_json);
            var result = JsonUtil.Deserializer<ApiDataResult<int>>(json);

            if (result == null)
                throw new Exception("功能数据删除失败!");
            if (!result.Success)
                throw new Exception(result.Message);
            if (result.Data == 0)
                throw new Exception("未删除任何数据");

            return result.Data;
        }

        public IEnumerable<FuncEntity> GetAllFunctions(string key = "")
        {
            string json = _funcAccess.GetAllFunctions(key);
            var result = JsonUtil.Deserializer<ApiDataResult<FuncEntity[]>>(json);
            if (result == null)
                throw new Exception("功能数据获取失败!");
            if (!result.Success)
                throw new Exception(result.Message);

            return result.Data;
        }
        public IEnumerable<FuncEntity> GetFunctionByIds(string key = "")
        {
            string json = _funcAccess.GetFunctionByIds(key);
            return this.GetResult<FuncEntity[]>(json);
        }

        public int Update(FuncEntity func)
        {
            string depart_json = System.Text.Json.JsonSerializer.Serialize(func);
            string json = _funcAccess.UpdateFunction(depart_json);
            var result = JsonUtil.Deserializer<ApiDataResult<int>>(json);

            if (result == null)
                throw new Exception("功能数据更新失败!");
            if (!result.Success)
                throw new Exception(result.Message);
            if (result.Data == 0)
                throw new Exception("未更新任何数据");

            return result.Data;
        }
    }
}
